import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

public class NetworkAdapterMonitor {

    private static final long THRESHOLD_SPEED = 100 * 1024; // 100 KB/s
    private static final long SUSTAINED_HIGH_SPEED_DURATION = 5000; // 5 seconds in milliseconds
    private static final long SUSTAINED_LOW_SPEED_DURATION = 200000; // 200 seconds in milliseconds

    private static String ethernet1;
    private static String ethernet2;
    private static String activeAdapter;
    private static Long highSpeedStart;
    private static Long lowSpeedStart;

    public static void main(String[] args) {
        ethernet1 = getAdapter("以太网1");
        ethernet2 = getAdapter("以太网2");

        if (ethernet1 == null || ethernet2 == null) {
            System.err.println("无法找到网卡 '以太网1' 或 '以太网2'");
            return;
        }

        enableNetworkAdapter(ethernet2);
        disableNetworkAdapter(ethernet1);
        activeAdapter = ethernet2;

        System.out.println("当前启用的网卡是：" + activeAdapter);

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                monitorNetworkSpeed();
            }
        }, 0, 1000); // Check every second
    }

    private static String getAdapter(String namePattern) {
        try {
            Process process = new ProcessBuilder("powershell", "/c", "Get-NetAdapter | Where-Object { $_.Status -eq 'Up' -and $_.Name -like '" + namePattern + "' } | Select-Object -First 1 -ExpandProperty Name").start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            return reader.readLine();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static void enableNetworkAdapter(String adapter) {
        try {
            new ProcessBuilder("powershell", "/c", "Enable-NetAdapter -Name '" + adapter + "' -Confirm:$false").start().waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void disableNetworkAdapter(String adapter) {
        try {
            new ProcessBuilder("powershell", "/c", "Disable-NetAdapter -Name '" + adapter + "' -Confirm:$false").start().waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static long getNetworkSpeed(String adapter) {
        try {
            Process process = new ProcessBuilder("powershell", "/c", "Get-NetAdapterStatistics -Name '" + adapter + "' | Select-Object -ExpandProperty ReceivedBytesPerSec").start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            long receiveSpeed = Long.parseLong(reader.readLine().trim());

            process = new ProcessBuilder("powershell", "/c", "Get-NetAdapterStatistics -Name '" + adapter + "' | Select-Object -ExpandProperty SentBytesPerSec").start();
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            long sendSpeed = Long.parseLong(reader.readLine().trim());

            return Math.max(receiveSpeed, sendSpeed);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    private static void monitorNetworkSpeed() {
        long currentSpeed = getNetworkSpeed(activeAdapter);
        System.out.println("当前网速：" + (currentSpeed / 1024) + " KB/s");

        long currentTime = System.currentTimeMillis();

        if (currentSpeed > THRESHOLD_SPEED) {
            if (highSpeedStart == null) {
                highSpeedStart = currentTime;
            } else if (currentTime - highSpeedStart >= SUSTAINED_HIGH_SPEED_DURATION) {
                lowSpeedStart = null; // Reset low speed monitoring
            }
        } else {
            if (highSpeedStart != null && currentTime - highSpeedStart >= SUSTAINED_HIGH_SPEED_DURATION) {
                if (lowSpeedStart == null) {
                    lowSpeedStart = currentTime;
                } else if (currentTime - lowSpeedStart >= SUSTAINED_LOW_SPEED_DURATION) {
                    // Switch network adapters
                    disableNetworkAdapter(activeAdapter);
                    enableNetworkAdapter(activeAdapter.equals(ethernet1) ? ethernet2 : ethernet1);
                    activeAdapter = activeAdapter.equals(ethernet1) ? ethernet2 : ethernet1;
                    System.out.println("切换网卡，当前启用的网卡是：" + activeAdapter);
                    highSpeedStart = null;
                    lowSpeedStart = null;
                }
            } else {
                highSpeedStart = null;
            }
        }
    }
}
